/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cratos.xxgram.platf.user;

import java.io.IOException;
import java.io.Serializable;
import java.net.HttpCookie;
import java.util.Map;
import java.util.logging.Level;

import javax.annotation.Resource;

import org.redkale.convert.json.JsonConvert;
import org.redkale.convert.json.JsonFactory;
import org.redkale.net.http.HttpContext;
import org.redkale.net.http.HttpMapping;
import org.redkale.net.http.HttpRequest;
import org.redkale.net.http.HttpResponse;
import org.redkale.net.http.WebServlet;
import org.redkale.net.http.WebSocketNode;
import org.redkale.service.RetResult;
import org.redkale.util.AnyValue;
import org.redkale.util.Comment;
import org.redkalex.weixin.WeiXinMPService;

import com.cratos.xxgram.platf.base.BaseServlet;
import com.cratos.xxgram.platf.base.RetCodes;
import com.cratos.xxgram.platf.base.UserInfo;
import com.cratos.xxgram.platf.message.MessageRecord;
import com.cratos.xxgram.platf.message.MessageService;
import com.cratos.xxgram.platf.notice.RandomCode;

/**
 * 用户模块的Servlet
 *
 * @author zhangjx
 */
@WebServlet({"/user/*"})
public class UserServlet extends BaseServlet {

	
    public static final String COOKIE_AUTOLOGIN = "UNF";

    @Resource
    private UserService service;

    //用于微信登录
    @Resource
    private WeiXinMPService wxService;

    @Resource
    private JsonConvert userConvert;

    @Resource
    private MessageService messageService;
    
    @Override
    public void init(HttpContext context, AnyValue config) {
        JsonFactory factory = JsonFactory.root().createChild();
        //当前用户查看自己的用户信息时允许输出隐私信息
        factory.register(UserInfo.class, false,"ecdhprivkey", "mobile", "rytoken", "rytime", "infotime", "ecdhpubkey");
        factory.register(UserDetail.class, false,"ecdhprivkey", "mobile", "rytoken", "rytime", "infotime", "ecdhpubkey");
        userConvert = factory.getConvert();
        super.init(context, config);
    }
    @Resource(name = "wsim")
    protected WebSocketNode webSocketNode;
    
    //用户注销
    @HttpMapping(url = "/user/logout", auth = true)
    public void logout(HttpRequest req, HttpResponse resp) throws IOException {
    	String sessionid = "";
        String connector = req.getHeader("CONNECTOR", "APP");
        UserInfo userInfo = req.currentUser();
        if (sessionid == null || sessionid.isEmpty()) {
            sessionid = req.getHeader("JSESSIONID");
        }
        if (sessionid == null || sessionid.isEmpty()) {
            sessionid = req.getHeader("jsessionid");
        }
        if (sessionid != null) {
            service.logout(sessionid);
        }
        HttpCookie cookie = new HttpCookie(COOKIE_AUTOLOGIN, "");
        cookie.setPath("/");
        cookie.setMaxAge(1);
        HttpCookie jsessionidCookie = new HttpCookie("JSESSIONID", "");
        jsessionidCookie.setPath("/");
        jsessionidCookie.setMaxAge(1);
        
        if (!"WEB".equalsIgnoreCase(connector)) {
              RetResult<MessageRecord> ret = service.logoutH5(userInfo);
              messageService.sendMessage(ret.getResult());
              //service.updateJpushRegid(userInfo, "");
        }
        
        // 发送 登出消息
        if (userInfo != null ) {
                 RetResult<MessageRecord> rets = service.disableH5Status(userInfo);
        	 messageService.sendMessage(rets.getResult());
        }
        
        resp.addCookie(cookie);
        resp.addCookie(jsessionidCookie);
        resp.finish("{\"success\":true}");
        logger.finest("logout =======>>>>> " + req +"==== userInfo =====" + userInfo);
        
    }
    
    @HttpMapping(url = "/user/logoutH5", auth = true)
    public void logoutH5(HttpRequest req, HttpResponse resp) throws IOException {
        UserInfo userInfo = req.currentUser();
        RetResult<MessageRecord> ret = service.logoutH5(userInfo);
        if (!ret.isSuccess()) resp.finish(ret);
        messageService.sendMessage(ret.getResult());
        resp.finish(RetResult.success());
    }

    /**
     * 用户登陆
     *
     * @param req
     * @param resp
     *
     * @throws IOException
     */
    @HttpMapping(url = "/user/login", auth = false)
    public void login(HttpRequest req, HttpResponse resp) throws IOException {
        LoginBean bean = req.getJsonParameter(LoginBean.class, "bean");
        if (bean == null) {
            bean = new LoginBean();
        }
        if (!bean.emptyPassword()) {
            bean.setPassword(UserService.secondPasswordMD5(bean.getPassword()));
        }
        bean.setLoginagent(req.getHeader("User-Agent"));
        bean.setLoginip(req.getRemoteAddr());
        String oldsessionid = req.getSessionid(false);
        if (oldsessionid != null && !oldsessionid.isEmpty()) {
            service.logout(oldsessionid);
        }
        bean.setSessionid(req.changeSessionid());
        RetResult<UserInfo> result = service.login(bean);
        if (result.isSuccess() && bean.emptyPassword()) {
            UserInfo userInfo = result.getResult();
            if (userInfo.getHaspwd() == 0) { //没设置密码
                bean.setPassword(UserService.secondPasswordMD5(UserInfo.md5(UserInfo.DEFAULT_PWD)));// 设置默认密码
            } else {
            	bean.setPassword(userInfo.getPassword());// 设置默认密码
            }
        }
        
        if (result.isSuccess()) { //必须是密码登录类
			if (bean.getCacheday() > 0 /* && bean.emptyCookieinfo() */) {  //保存N天 
                UserInfo info = result.getResult();
                int age = bean.getCacheday() * 24 * 60 * 60;
                String key = (bean.emptyApptoken() ? "" : (bean.getApptoken() + "#")) + info.getUser36id() + "$0" + bean.getPassword() + "?" + age + "-" + System.currentTimeMillis();
                HttpCookie cookie = new HttpCookie(COOKIE_AUTOLOGIN, UserService.encryptAES(key));
                cookie.setHttpOnly(true);
                cookie.setPath("/");
                cookie.setMaxAge(age);
                resp.addCookie(cookie);
            }
        }
        if (result.isSuccess()) {
            result.attach("sessionid", bean.getSessionid());
        }
        logger.log(Level.FINEST, "登陆结果: " + result.toString());
        resp.finishJson(userConvert, result);
    }

    @HttpMapping(url = "/user/signup", auth = false)   //待定
    public void signup(HttpRequest req, HttpResponse resp) throws IOException {
        long s = System.currentTimeMillis();
        Map<String, String> map = convert.convertFrom(JsonConvert.TYPE_MAP_STRING_STRING, req.getParameter("bean"));
        RetResult<RandomCode> ret = null;
        String beanaccount;
        UserDetail bean = new UserDetail();
        if (map.containsKey("mobile")) {
            bean.setMobile(map.get("mobile"));
            bean.setNation(Integer.parseInt(map.get("nation")));
            beanaccount = bean.getMobile();
            ret = service.checkRandomCode(bean.getNation() + bean.getMobile(), map.get("vercode"), RandomCode.TYPE_SMSREG);
            if (!ret.isSuccess()) {
                resp.finishJson(ret);
                return;
            }
        } else {
            bean.setAccount(map.getOrDefault("account", ""));
            beanaccount = bean.getAccount();
        }
        bean.setUsername(map.getOrDefault("username", ""));
        bean.setApptoken(map.getOrDefault("apptoken", ""));
        bean.setPassword(map.getOrDefault("password", UserInfo.md5(UserInfo.DEFAULT_PWD)));//默认密码md5 不可见字符
        bean.setJpregid(map.getOrDefault("jpregid", ""));//设备id
        bean.setRegaddr(req.getRemoteAddr());
        bean.setRegagent(req.getHeader("User-Agent", ""));
      
        RetResult<UserInfo> rr = service.register(bean);
        if (rr.isSuccess()) {
            if (ret != null) {
                ret.getResult().setUserid(rr.getResult().getUserid());
                service.removeRandomCode(ret.getResult());
            }
            LoginBean loginbean = new LoginBean();
            loginbean.setAccount(beanaccount);
            loginbean.setApptoken(bean.getApptoken());
            loginbean.setSessionid(req.changeSessionid());
            loginbean.setNation(Integer.parseInt(map.getOrDefault("nation", "86")));
            loginbean.setLoginagent(req.getHeader("User-Agent"));
            if (rr.getResult().getHaspwd() == 0) { //没设置密码
                loginbean.setPassword(UserService.secondPasswordMD5(UserInfo.md5(UserInfo.DEFAULT_PWD)));// 设置默认密码
            }
            if (map.containsKey("cacheday")) {
                loginbean.setCacheday(Integer.parseInt(map.getOrDefault("cacheday", "0")));
            }
            loginbean.setLoginip(req.getRemoteAddr());
            loginbean.setLoginmode(LoginBean.LOGIN_WITH_REGISTER_SUCCESS);
            rr = service.login(loginbean);
            // 返回sessionid
            if (rr.isSuccess()) {
                rr.attach("sessionid", loginbean.getSessionid());
                if (loginbean.getCacheday() > 0 && loginbean.emptyCookieinfo()) {  //保存N天 
                    UserInfo info = rr.getResult();
                    int age = loginbean.getCacheday() * 24 * 60 * 60;
                    String key = (loginbean.emptyApptoken() ? "" : (bean.getApptoken() + "#")) + info.getUser36id() + "$0" + bean.getPassword() + "?" + age + "-" + System.currentTimeMillis();
                    HttpCookie cookie = new HttpCookie(COOKIE_AUTOLOGIN, UserService.encryptAES(key));
                    cookie.setHttpOnly(true);
                    cookie.setPath("/");
                    cookie.setMaxAge(age);
                    resp.addCookie(cookie);
                }
            }
        }
        long e = System.currentTimeMillis() - s;
        if (e > 500) {
            logger.warning("/user/signup cost " + e / 1000.0 + " seconds " + bean);
        }
        resp.finishJson(userConvert, rr);
    }

    /**
     * 修改密码
     *
     * @param req
     * @param resp
     *
     * @throws IOException
     */
    @HttpMapping(url = "/user/updatepwd")
    public void updatepwd(HttpRequest req, HttpResponse resp) throws IOException {
        UserPwdBean bean = req.getJsonParameter(UserPwdBean.class, "bean");
        UserInfo curr = req.currentUser();
        if (curr != null) {
            bean.setSessionid(req.getSessionid(false));
        }
        RetResult<UserInfo> result = service.updatePwd(bean);
        if (result.isSuccess() && curr == null) { //找回的密码
            curr = result.getResult();
            LoginBean loginbean = new LoginBean();
            loginbean.setAccount(curr.getMobile());
            loginbean.setPassword(UserService.secondPasswordMD5(bean.getNewpwd()));
            loginbean.setSessionid(req.changeSessionid());
            loginbean.setLoginagent(req.getHeader("User-Agent"));
            loginbean.setLoginip(req.getRemoteAddr());
            result = service.login(loginbean);
        }
        String autologin = req.getCookie(COOKIE_AUTOLOGIN);
        if (result.isSuccess() && autologin != null) {
            autologin = UserService.decryptAES(autologin);
            if (autologin.contains("$0")) { //表示COOKIE_AUTOLOGIN 为密码类型存储
                String newpwd = UserService.secondPasswordMD5(bean.getNewpwd());
                int wen = autologin.indexOf('?');
                int mei = autologin.indexOf('$');
                String key = autologin.substring(0, mei + 2) + newpwd + autologin.substring(wen);
                HttpCookie cookie = new HttpCookie(COOKIE_AUTOLOGIN, UserService.encryptAES(key));
                cookie.setHttpOnly(true);
                cookie.setPath("/");
                String time = autologin.substring(wen + 1);
                int fen = time.indexOf('-');
                int age = Integer.parseInt(time.substring(0, fen)); //秒数
                long point = Long.parseLong(time.substring(fen + 1)); //毫秒数
                cookie.setMaxAge(age - (System.currentTimeMillis() - point) / 1000);
                resp.addCookie(cookie);
            }
        }
        resp.finishJson(result);
    }
    
     /**
     * 修改密码
     *
     * @param req
     * @param resp
     *
     * @throws IOException
     */
    @HttpMapping(url = "/user/updatePassword")
    public void updatePassword(HttpRequest req, HttpResponse resp) throws IOException {
        UserPwdBean bean = req.getJsonParameter(UserPwdBean.class, "bean");
        UserInfo curr = req.currentUser();
        if (curr != null) {
            bean.setSessionid(req.getSessionid(false));
        }
        RetResult<UserInfo> result = service.updatePassword(curr, bean);
        resp.finishJson(result);
    }
    @HttpMapping(url = "/user/resetpwd", auth = false)
    public void resetpwd(HttpRequest req, HttpResponse resp) throws IOException {
        UserPwdBean bean = req.getJsonParameter(UserPwdBean.class, "bean");
        UserInfo curr = req.currentUser();
        if (curr != null) {
            bean.setSessionid(req.getSessionid(false));
        }
        RetResult<UserInfo> result = service.resetPwd(bean);
        if (result.isSuccess() && curr == null) { //找回的密码
            curr = result.getResult();
            LoginBean loginbean = new LoginBean();
            loginbean.setAccount(curr.getMobile());
            loginbean.setPassword(UserService.secondPasswordMD5(bean.getNewpwd()));
            loginbean.setSessionid(req.changeSessionid());
            loginbean.setLoginagent(req.getHeader("User-Agent"));
            loginbean.setLoginip(req.getRemoteAddr());
            result = service.login(loginbean);
        }
        String autologin = req.getCookie(COOKIE_AUTOLOGIN);
        if (result.isSuccess() && autologin != null) {
            autologin = UserService.decryptAES(autologin);
            if (autologin.contains("$0")) { //表示COOKIE_AUTOLOGIN 为密码类型存储
                String newpwd = UserService.secondPasswordMD5(bean.getNewpwd());
                int wen = autologin.indexOf('?');
                int mei = autologin.indexOf('$');
                String key = autologin.substring(0, mei + 2) + newpwd + autologin.substring(wen);
                HttpCookie cookie = new HttpCookie(COOKIE_AUTOLOGIN, UserService.encryptAES(key));
                cookie.setHttpOnly(true);
                cookie.setPath("/");
                String time = autologin.substring(wen + 1);
                int fen = time.indexOf('-');
                int age = Integer.parseInt(time.substring(0, fen)); //秒数
                long point = Long.parseLong(time.substring(fen + 1)); //毫秒数
                cookie.setMaxAge(age - (System.currentTimeMillis() - point) / 1000);
                resp.addCookie(cookie);
            }
        }
        resp.finishJson(result);
    }

    //更新用户手机号码
    @HttpMapping(url = "/user/updatemobile")
    public void updatemobile(HttpRequest req, HttpResponse resp) throws IOException {
        UserInfo user = req.currentUser();
        Integer nation = Integer.parseInt(req.getParameter("nation","86"));
        resp.finishJson(service.updateMobile(user.getUserid(), nation, req.getParameter("mobile"), req.getParameter("vercode"), req.getParameter("precode")));
    }

    //更新用户昵称
    @HttpMapping(url = "/user/updateusername")
    public void updateUsername(HttpRequest req, HttpResponse resp) throws IOException {
        UserInfo user = req.currentUser();
        resp.finishJson(service.updateUsername(user.getUserid(), req.getParameter("username")));
    }

    //更新用户头像
    @HttpMapping(url = "/user/updateface", auth = true)
    public void updateFace(HttpRequest req, HttpResponse resp) throws IOException {
        UserInfo user = req.currentUser();
        
        resp.finishJson(service.updateFace(user.getUserid(), req.getParameter("face")));
    }

    //更新用户头像
    @HttpMapping(url = "/user/updateEcdhKeyPair", auth = true)
    public void updateEcdhKeyPair(HttpRequest req, HttpResponse resp) throws IOException {
        UserInfo user = req.currentUser();
        resp.finishJson(service.updateEcdhKeyPair(user));
    }

    //更新设备ID
    @HttpMapping(url = "/user/updateapptoken")
    public void updateApptoken(HttpRequest req, HttpResponse resp) throws IOException {
        String s = req.getRequstURILastPath();
        if ("updateapptoken".equalsIgnoreCase(s)) {
            s = "";
        }
        UserInfo user = req.currentUser();
        resp.finishJson(service.updateApptoken(user.getUserid(), req.getParameter("appos", req.getRequstURIPath("appos:", "")), req.getParameter("apptoken", s)));
    }

    //更新性别
    @HttpMapping(url = "/user/updategender/")
    public void updateGender(HttpRequest req, HttpResponse resp) throws IOException {
        UserInfo user = req.currentUser();
        resp.finishJson(service.updateGender(user.getUserid(), Short.parseShort(req.getRequstURILastPath())));
    }

    //发送修改密码验证码
    @HttpMapping(url = "/user/smspwdcode")
    public void smscode(HttpRequest req, HttpResponse resp) throws IOException {
        smsvercode(RandomCode.TYPE_SMSPWD, req, resp);
    }

    //发送忘记密码验证码
    @HttpMapping(url = "/user/smsfpwcode", auth = false)
    public void smsfot(HttpRequest req, HttpResponse resp) throws IOException {
        smsvercode(RandomCode.TYPE_SMSPWD, req, resp);
    }

    //发送手机修改验证码
    @HttpMapping(url = "/user/smsmobcode")
    public void smsmob(HttpRequest req, HttpResponse resp) throws IOException {
        smsvercode(RandomCode.TYPE_SMSMOB, req, resp);
    }

    //发送原手机验证码
    @HttpMapping(url = "/user/smsodmcode")
    public void smsodm(HttpRequest req, HttpResponse resp) throws IOException {
        smsvercode(RandomCode.TYPE_SMSODM, req, resp);
    }

    //发送手机注册验证码
    @HttpMapping(url = "/user/smsregcode", auth = false)
    public void smsreg(HttpRequest req, HttpResponse resp) throws IOException {
        smsvercode(RandomCode.TYPE_SMSREG, req, resp);
    }

    //发送手机登录验证码
    @HttpMapping(url = "/user/smslgncode", auth = false)
    public void smslgn(HttpRequest req, HttpResponse resp) throws IOException {
        //检查用户是否存在
        RetResult rsResult = null;
        if (!(rsResult = checkUserInfo(req, resp)).isSuccess()) {
            resp.finishJson(rsResult);
        }
        smsvercode(RandomCode.TYPE_SMSLGN, req, resp);
    }

    @Comment("检查用户是否存在")
    private RetResult checkUserInfo(HttpRequest req, HttpResponse resp) {
          String mobile = req.getRequstURIPath("mobile:", req.getParameter("mobile"));
        int nation = Integer.parseInt(req.getParameter("nation", "86"));
        UserInfo userInfo = service.findUserInfoByMobile(nation, mobile);
        if (userInfo == null) {
            return  RetCodes.retResult(RetCodes.RET_USER_NOTEXIT_FIRIND);
        }
        return RetResult.success();
    }
    private void smsvercode(final short type, HttpRequest req, HttpResponse resp) throws IOException {
        String mobile = req.getRequstURIPath("mobile:", req.getParameter("mobile"));
        int nation = Integer.parseInt(req.getParameter("nation", "86"));
        if (type == RandomCode.TYPE_SMSODM) { //给原手机号码发送验证短信
            UserInfo user = req.currentUser();
            if (user != null) {
                mobile = user.getMobile();
            }
        }
        RetResult rr = service.smscode(type, nation, mobile);
        if (finest) {
            logger.finest(req.getRequestURI() + ", mobile = " + mobile + "---->" + rr);
        }
        resp.finishJson(rr);
    }

    //检测账号是否有效, 返回t0表示可用.给新用户注册使用
    @HttpMapping(url = "/user/checkaccount/", auth = false)
    public void checkAccount(HttpRequest req, HttpResponse resp) throws IOException {
        resp.finishJson(RetCodes.retResult(service.checkAccount(req.getRequstURILastPath())));
    }

    //检测手机号码是否有效, 返回0表示可用.给新用户注册使用
    @Deprecated(since = "下个版本删除")
    @HttpMapping(url = "/user/checkmobile/", auth = false)
    public void checkMobile(HttpRequest req, HttpResponse resp) throws IOException {
        resp.finishJson(RetCodes.retResult(service.checkMobile(86, req.getRequstURILastPath())));
    }

    //检测邮箱地址是否有效, 返回0表示可用.给新用户注册使用
    @HttpMapping(url = "/user/checkemail/", auth = false)
    public void checkEmail(HttpRequest req, HttpResponse resp) throws IOException {
        resp.finishJson(RetCodes.retResult(service.checkEmail(req.getRequstURILastPath())));
    }

    //验证短信验证码
    @HttpMapping(url = "/user/checkcode", auth = false)
    public void checkcode(HttpRequest req, HttpResponse resp) throws IOException {
        String mobile = req.getRequstURIPath("mobile:", req.getParameter("mobile"));
        String nation = req.getRequstURIPath("nation:", req.getParameter("nation","86"));
        String vercode = req.getRequstURIPath("vercode:", req.getParameter("vercode"));
        RetResult<RandomCode> ret = service.checkRandomCode(nation + mobile, vercode, (short) 0);
        resp.finishJson(RetCodes.retResult(ret.getRetcode()));
    }

    //获取当前用户基本信息
    @HttpMapping(url = "/user/myinfo")
    public void myinfo(HttpRequest req, HttpResponse resp) throws IOException {
        UserInfo user = req.currentUser();
        resp.finishJson(user);
    }

    //获取当前用户基本信息（js格式）
    @HttpMapping(url = "/user/js/myinfo", auth = false)
    public void myinfojs(HttpRequest req, HttpResponse resp) throws IOException {
        UserInfo user = req.currentUser();
        resp.setContentType("application/javascript; charset=utf-8");
        if (user == null) {
            resp.finish("var userself = null;");
        } else {
            resp.finish("var userself = " + convert.convertTo(user) + ";");
        }
    }

    //获取个人基本信息
    @HttpMapping(url = "/user/info/")
    public void info(HttpRequest req, HttpResponse resp) throws IOException {
        resp.finishJson(service.findUserInfo(Integer.parseInt(req.getRequstURILastPath())));
    }

    @Comment("根据用户号码查询用户信息")
    @HttpMapping(url = "/user/loadByMobile")
    public void loadByMobile(HttpRequest req, HttpResponse resp) {
        int mobilenation = Integer.parseInt(req.getParameter("mobilenation:", "86"));
        resp.finishJson(RetResult.success(service.findUserInfoByMobile(mobilenation, req.getRequstURILastPath())));
    }

    //获取当前用户详细信息
    @HttpMapping(url = "/user/mydetail")
    public void mydetail(HttpRequest req, HttpResponse resp) throws IOException {
        UserInfo user = req.currentUser();
        resp.finish(userConvert.convertTo(service.findUserDetail(user.getUserid())));
    }

    //获取当前用户详细信息（js格式）
    @HttpMapping(url = "/user/js/mydetail", auth = false)
    public void mydetailjs(HttpRequest req, HttpResponse resp) throws IOException {
        UserInfo user = req.currentUser();
        resp.setContentType("application/javascript; charset=utf-8");
        if (user == null) {
            resp.finish("var userdetailself = null;");
        } else {
            resp.finish("var userdetailself = " + userConvert.convertTo(service.findUserDetail(user.getUserid())) + ";");
        }
    }

    @HttpMapping(url = "/user/check", auth = true)
    public void check(HttpRequest req, HttpResponse resp) throws IOException {
    	String CONNECTOR = req.getHeader("CONNECTOR", "");
    	UserInfo user = req.currentUser();
    	if ("WEB".equalsIgnoreCase(CONNECTOR)) {
    		// web 在线
    		user.setOnlineterminal(user.getOnlineterminal() | 2);
		} else if("Android".equals(CONNECTOR) 
				|| CONNECTOR.equalsIgnoreCase("IOS")){
			// APP 在线
			user.setOnlineterminal(user.getOnlineterminal() | 1);
		}
        resp.finishJson(RetResult.success(user));
    }
    
    @HttpMapping(comment = "我的 - 更新用户资料", url = "/user/updateUserInfo", auth = true)
    public void updateUserInfo(HttpRequest req, HttpResponse resp) throws IOException {
        UserInfo user = req.currentUser();
        String field = req.getParameter("field");
        Serializable value = (Serializable)req.getParameter("value");
        if ("gender".equalsIgnoreCase(field)) {
        	 value = Short.valueOf(req.getParameter("value"));
        }
        if (field == null || value == null) {
            resp.finishJson(RetCodes.retInfo(RetCodes.RET_PARAMS_ILLEGAL));
            return;
        }
        resp.finishJson(service.updateUserInfo(user.getUserid(), field, value));
    }

    @HttpMapping(comment = "我的 - 完善个人资料", url = "/user/improvePersonalInfo", auth = true)
    public void improvePersonalInfo(HttpRequest req, HttpResponse res) {
        UserInfo user = req.currentUser();
        UserDetail userDetail = req.getJsonParameter(UserDetail.class, "bean");
        userDetail.setUserid(user.getUserid());
        res.finishJson(service.improvePersonalInfo(userDetail));
    }
    
    @HttpMapping(comment = "通知 - 更新用户密码", url = "/user/updateLockValue", auth = true)
    public void updateLockValue(HttpRequest req, HttpResponse res) {
        UserInfo user = req.currentUser();
        String oldlockpwd  = req.getParameter("oldlockpwd", "");
        String pwd  = req.getParameter("lockpwd", "");
        res.finishJson(service.updateLockpwd(user, pwd, oldlockpwd));
    }
    
 
    @HttpMapping(comment = "通知 - 更新销毁密码", url = "/user/updatedDestroypwd", auth = true)
    public void updatedDestroypwd(HttpRequest req, HttpResponse res) {
        UserInfo user = req.currentUser();
        String pwd = req.getRequstURILastPath();
        // 跟新销毁密码配置
        res.finishJson(service.updateUserInfo(user.getUserid(), "destroypwd", pwd));
    }
    
    @HttpMapping(comment = "销毁账号", url = "/user/destroyAccount", auth = true)
    public void destroyAccount(HttpRequest req, HttpResponse res) {
        UserInfo user = req.currentUser();
        String oldsessionid = req.getSessionid(false);
        RetResult<MessageRecord> ret = service.logoutH5(user);
        if (ret.isSuccess()) {
             messageService.sendMessage(ret.getResult());
        }
        //先注销  在销毁账号
        if (oldsessionid != null 
                    && !oldsessionid.isEmpty() 
                    ||  ((oldsessionid = req.getParameter("jsessionid", req.getParameter("JSESSIONID"))) != null 
                        && !oldsessionid.isEmpty())) {
            service.logout(oldsessionid);
        }
        res.finishJson(service.destroyAccount(user));
    }
    
    
    @HttpMapping(comment = "通知 - 更新系统配置", url = "/user/updateSystemSetting", auth = true)
    public  void updateSysSetting(HttpRequest req, HttpResponse res) {
        UserInfo user = req.currentUser();
        int index =  Integer.parseInt(req.getParameter("index"));
        int value = Integer.parseInt(req.getParameter("value"));
        res.finishJson(service.updateSystemSetting(user, index, value));
    }
  
    @HttpMapping(url = "/user/preWebLogin", auth = false,  comment = "获取登录二维码")
    public void preWebLogin(HttpRequest req, HttpResponse resp) throws IOException {
        resp.finishJson(service.preWebLogin());
    }
    
    @HttpMapping(url = "/user/scanWebLogin", auth = true, comment = "手机已扫描状态")
    public void scanWebLogin(HttpRequest req, HttpResponse resp) throws IOException {
        resp.finishJson(service.scanWebLogin(req.getParameter("uuidKey", "")));
    }
 
    @HttpMapping(url = "/user/okWebLogin", auth = true, comment = "手机端同意一登陆")
    public void okWebLogin(HttpRequest req, HttpResponse resp) throws IOException {
    	 logger.finest("req ====>>>>>>> " + req);
    	 RetResult<UserInfo> retResult = autoLogin(req);
    	 String autologin = req.getCookie(UserServlet.COOKIE_AUTOLOGIN, req.getParameter(UserServlet.COOKIE_AUTOLOGIN, req.getHeader(UserServlet.COOKIE_AUTOLOGIN, "")));
    	 String sessionid = "";
    	 logger.finest("ret ======>>>>>>" + retResult);
    	 if (retResult.isSuccess()) {
    		 sessionid = retResult.getResult().getJsessionid();
    	 } else {
			//    		 if (sessionid == null || sessionid.isEmpty()) {
			//                 sessionid = req.getHeader("JSESSIONID", req.getHeader("jsessionid"));
			//             }
    		 resp.finishJson(RetCodes.retResult(RetCodes.RET_INVALIDATE_UNF_SCAN));
    		 return;
    	 }
        logger.finest(String.format("session=%s, UNF=%s", sessionid, autologin));
        // 统一登录直接下线网页版
        if (UserService.AGREE_LOGIN.equalsIgnoreCase( req.getParameter("loginstatus", ""))) {
              UserInfo userInfo = req.currentUser();
            RetResult<MessageRecord> ret = service.logoutH5(userInfo);
            if (!ret.isSuccess()) resp.finish(ret);
            messageService.sendMessage(ret.getResult());
        }
        resp.finishJson(service.okWebLogin(req.getParameter("uuidKey", ""), sessionid + "#" + autologin, req.getParameter("loginstatus", "")));
    }
    
    
    @HttpMapping(url = "/user/checkScanStatus", auth = false,  comment = "轮询检查扫描状态")
    public void checkScanStatus(HttpRequest req, HttpResponse resp) throws IOException {
        resp.finishJson(service.checkScanStatus(req.getParameter("uuidKey", "")));
    }
    
    
    @HttpMapping(url = "/user/checkWebLogin", auth = false,  comment = "轮询检验登录结果")
    public void checkWebLogin(HttpRequest req, HttpResponse resp) throws IOException {
        resp.finishJson(service.checkWebLogin(req.getParameter("uuidKey", "")));
    }
    
    @HttpMapping(url = "/user/updateJpushRegid", auth = true)
    public void updateJpushRegid(HttpRequest req, HttpResponse resp) throws IOException {
        UserInfo user = req.currentUser();
        resp.finishJson(service.updateJpushRegid(user, req.getParameter("jpregid","")));
    }
    
    /*****************************************oss 相关接口**************************************************/
    @Comment("OSS 在线状态 接口")
    @HttpMapping(url = "/user/updatestatus", auth = false)
    public void updatestatus(HttpRequest req, HttpResponse resp) throws IOException {
        resp.finishJson(service.updateStatus(req.getIntParameter("userid", 100), req.getShortParameter("status", 10)));
    }
    
    @Comment("OSS 在线状态 接口")
    @HttpMapping(url = "/user/resetPwdByAdmin", auth = false)
    public void resetPwdByAdmin(HttpRequest req, HttpResponse resp) throws IOException {
        resp.finishJson(service.resetPwdByAdmin(req.getIntParameter("userid", 100)));
    }
    /*****************************************oss 相关接口**************************************************/
}
